<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------

namespace app\erp\admin;

use app\admin\controller\Admin;
use think\Db;
use app\common\builder\ZBuilder;
/**
 * 服务分类管理
 * @package app\cms\admin
 */
class ServiceClass extends Admin
{
    /**
     * 首页
     * @author shiqiang
     * @return mixed
     */
    public function index(){	
		cookie('__forward__', $_SERVER['REQUEST_URI']);
		
		$list = model('ErpServiceClass', 'model') -> getClass();
		
		$btn_video = [
			'title' => '查看服务',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('service/index', ['class_id' => '__id__', '_pop' => 1]),
		];
		
		$btn_access = [
			'title' => '添加',
			'icon'  => 'fa fa-fw fa-key',
			'class' => 'btn btn-xs btn-default',
			'href'  => url('add', ['pid' => '__id__']),
		];
		
		 $btn_excel = [
			 'title' => '导入Excel',
			 'icon'  => 'fa fa-plus-circle',
			 'class' => 'btn btn-primary',
			 'href'  => url('upload_excel'),
		 ];

		// 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('服务分类') // 设置页面标题
            ->setTableName('erp_service_class') // 设置数据表名
            ->addColumns([ // 批量添加列
                ['id', 'id'],
                ['level', '级别'],
				// ['title_display', '分类标题(商品数量)'],
				['title_display', '分类标题'],
				['code', '编码'],
				['class_img', '图片', 'img_url'],
                ['sort', '排序','text.edit'],
                ['right_button', '操作', 'btn']
            ])
            ->addFilter(['report_status']) // 添加筛选
			->addTopButton('add', '', true) // 批量添加顶部按钮
//            ->addTopButton('btn_excel', $btn_excel, true) // 批量添加顶部按钮
			->addRightButton('btn_access', $btn_access, true) // 添加授权按钮
			->addRightButton('edit', '',true) // 批量添加右侧按钮
			->addRightButton('delete') // 批量添加右侧按钮
			->addRightButton('custom', $btn_video, true) // 查看视频
			->replaceRightButton(['level' => 2], '', 'btn_access')
			->setRowList($list) // 设置表格数据,
            ->fetch(); // 渲染页面
    }
	
	 /**
     * 新增
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function add($pid = ''){  
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			$data = $this->request->post('', null, 'trim');
			
			$pid        	= isset($data['pid']) ? $data['pid'] : '';
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$code 	 		= isset($data['code']) ? $data['code'] : '';
			$class_img 	 	= isset($data['class_img']) ? $data['class_img'] : '';
			//数据验证
			$Validate = validate('ServiceClass', 'validate');
			if( !$Validate -> scene('service_class_add') -> check($data) ){
				$this->error($Validate -> getError());
			}
			
			//业务逻辑
			$map = [];
			$map['pid'] = $pid;
			$map['title'] = $title;
			$class_title = model('ErpServiceClass') -> where($map) -> find(); //标题
			if(!empty($class_title)){
				$this->error('分类标题重复，无法添加');
			}
			
			$class_code = model('ErpServiceClass') -> where('code', $code) -> find();//编码
			if(!empty($class_code)){
				$this->error('分类编码重复，无法添加');
			}

            //图片上传阿里云
            if($class_img != ''  && strpos($class_img,'serviceclass/') ==false
            ){
                $rel_logo_pic = get_aliyun_pic_path($class_img,'serviceclass/');
                if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                $class_img  = $rel_logo_pic['data']['info']['url'];
            }
			
			$rel = model('ErpServiceClass') -> addData($pid, $title, $sort, $code, $class_img);
			if($rel['code'] == 200){
				$id = $rel['data'];
				$path = $id;
				if($pid > 0){
					$father_path = model('ErpServiceClass') -> find($pid) -> path;//上级path
					$path = $father_path . '-' .$path;//重组path
				}
				model('ErpServiceClass') -> where('id', $id) -> update(['path' => $path]);

				$this->success('新增成功', null, '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}

        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增分类')
            ->addFormItems([
                ['select', 'pid', '所属上级', '所属上级分类', model('ErpServiceClass') -> getMenuTree(0, ''), $pid],
                ['text', 'title', '分类标题'],
                ['text', 'code', '分类编码'],
            ])
            ->addText('sort', '排序', '', 100)
            ->addJcrop('class_img', '分类图片')
            ->setTrigger('auto_create', '1', 'child_node', false)
            ->fetch();
    }
	
	/**
     * 编辑
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function edit($id = 0, $pid = ''){   
		if ($id === 0) $this->error('缺少参数');
		// 保存数据
		if ($this->request->isPost()) {
			//数据接收
			
			$data = $this->request->post('', null, 'trim');
			$data['id'] = $id;
			$pid        	= isset($data['pid']) ? $data['pid'] : 0;
			$title    		= isset($data['title']) ? $data['title'] : '';
			$sort 	 		= isset($data['sort']) ? $data['sort'] : '';
			$code 	 		= isset($data['code']) ? $data['code'] : '';
			$path 	 		= isset($data['path']) ? $data['path'] : '';
			$class_img 	 	= isset($data['class_img']) ? $data['class_img'] : '';

			//数据验证
			$Validate = validate('ServiceClass', 'validate');
			if( !$Validate -> scene('service_class_edit') -> check($data) ){
				$this->error($Validate -> getError());
			}
			
			//业务逻辑
			$map = [
				['id', '<>', $id],
				['pid', '=', $pid],
				['title', '=', $title],
			];
			$list_class = model('ErpServiceClass') -> where($map) -> find();//标题
			if(!empty($list_class)){
				$this->error('分类标题重复，无法修改');
			}
			$map = [];
			$map = [
				['id', '<>', $id],
				['code', '=', $code],
			];
			$class_code = model('ErpServiceClass') -> where($map) -> find();//编码
			if(!empty($class_code)){
				$this->error('分类编码重复，无法添加');
			}

            //图片上传阿里云
            if($class_img != '' && strpos($class_img,'serviceclass/') ==false){
                $rel_logo_pic = get_aliyun_pic_path($class_img,'serviceclass/');
                if($rel_logo_pic['code'] != 200) $this->error('图片上传失败');
                $class_img  = $rel_logo_pic['data']['info']['url'];
            }
			$rel = model('ErpServiceClass') -> editData($id ,$pid, $title, $sort, $code, $class_img);
			if($rel['code'] == 200){
				$new_path = $id;
				if($pid > 0){
					$father_path = model('ErpServiceClass') -> find($pid) -> path;//上级path
					$new_path = $father_path . '-' .$new_path;//重组path
				}
				$childs_path = model('ErpServiceClass') -> getChildsPath($id);//所有子集path
				$list = [];
				foreach($childs_path as $key => $value){//下级分类path重组
					$childs_new_path['id'] = $key;
					$childs_new_path['path'] = str_replace($path, $new_path, $value);
					$list[] = $childs_new_path;
				}
				$list[] = ['id' => $id, 'path' => $new_path]; //插入条修改信息
				model('ErpServiceClass') -> saveAll($list);
				// model('ErpServiceClass') -> where('id', $id) -> update(['path' => $new_path]);

				$this->success('修改成功', null, '_parent_reload');
			}else{
				$this->error($rel['message']);
			}
		}
		
		$info = model('ErpServiceClass') -> find($id);
		$class_title = $info['pid'] == '' ? '顶级节点' : model('ErpServiceClass') -> find($info['pid']) -> title;
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑分类')
            ->addFormItems([
                ['text', 'pid_title', '所属上级', '所属上级分类', $class_title, '', 'readonly="readonlys"'],
                ['text', 'title', '分类标题'],
                ['text', 'code', '分类编码'],
                ['jcrop_oss', 'class_img', '分类图片'],
            ])
			->addHidden('pid', $info['pid'])
            ->addText('sort', '排序')
			->addHidden('path')
			//->addJcrop('class_img', '')
            ->setTrigger('auto_create', '1', 'child_node', false)
			->setFormData($info)
            ->fetch();
    }
	
	/**
     * 删除
     * @author shiqiang <976162041@qq.com>
     * @return mixed
     * @throws \think\Exception
     */
    public function delete($ids = []){ 
        // $class = model('ErpServiceClass') -> where('id', $ids)->find();
		
		// 获取所有后辈id
        $class_childs = model('ErpServiceClass') -> getChildsId($ids);
		// 要删除的所有id
        $all_ids = array_merge([(int)$ids], $class_childs);
		$rel = model('ErpServiceClass') -> destroy($all_ids);
        if ($rel) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

}

